{% extends 'base.html' %}
{% load static %}

{% block title %}网络设备管理{% endblock %}

{% block content %}
<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">网络设备管理</h1>
    
    <!-- 操作按钮 -->
    <div class="mb-4">
        <button class="btn btn-primary" onclick="location.href='{% url 'network_device_add' %}'">
            <i class="fas fa-plus"></i> 添加设备
        </button>
        <button class="btn btn-success" onclick="location.href='{% url 'download_network_template' %}'">
            <i class="fas fa-download"></i> 下载模板
        </button>
        <button class="btn btn-info" onclick="location.href='{% url 'import_network_devices' %}'">
            <i class="fas fa-upload"></i> 批量导入
        </button>
        <button class="btn btn-warning" onclick="location.href='{% url 'export_network_devices' %}'">
            <i class="fas fa-file-export"></i> 导出设备
        </button>
        <div class="btn-group">
            <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                批量操作
            </button>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="#" onclick="batchAction('enable')">启用</a></li>
                <li><a class="dropdown-item" href="#" onclick="batchAction('disable')">禁用</a></li>
                <li><a class="dropdown-item" href="#" onclick="batchAction('delete')">删除</a></li>
            </ul>
        </div>
    </div>

    <!-- 设备列表卡片 -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">网络设备列表</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="networkDeviceTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th width="30px">
                                <input type="checkbox" id="selectAll">
                            </th>
                            <th>设备名称</th>
                            <th>IP地址</th>
                            <th>设备类型</th>
                            <th>状态</th>
                            <th>CPU使用率</th>
                            <th>内存使用率</th>
                            <th>最后更新</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for device in devices %}
                        <tr data-id="{{ device.id }}">
                            <td>
                                <input type="checkbox" class="device-checkbox" value="{{ device.id }}">
                            </td>
                            <td>{{ device.name }}</td>
                            <td>{{ device.ip_address }}</td>
                            <td>{{ device.get_device_type_display }}</td>
                            <td>
                                <span class="badge {% if device.status == 'enabled' %}bg-success{% else %}bg-danger{% endif %}">
                                    {{ device.get_status_display }}
                                </span>
                            </td>
                            <td class="cpu-usage">
                                {% if device.snmp_cpu_usage is not None %}
                                <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                                    <div class="progress-bar progress-bar-striped" role="progressbar" 
                                         style="width: {{ device.snmp_cpu_usage }}%;
                                                {% if device.snmp_cpu_usage > 90 %}
                                                background-color: #dc3545;
                                                {% elif device.snmp_cpu_usage > 70 %}
                                                background-color: #ffc107;
                                                {% else %}
                                                background-color: #198754;
                                                {% endif %}">
                                    </div>
                                    <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                                                display: flex; align-items: center; justify-content: center;
                                                color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                                        {{ device.snmp_cpu_usage|floatformat:1 }}%
                                    </div>
                                </div>
                                {% else %}
                                --
                                {% endif %}
                            </td>
                            <td class="memory-usage">
                                {% if device.snmp_memory_usage is not None %}
                                <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                                    <div class="progress-bar progress-bar-striped" role="progressbar" 
                                         style="width: {{ device.snmp_memory_usage }}%;
                                                {% if device.snmp_memory_usage > 90 %}
                                                background-color: #dc3545;
                                                {% elif device.snmp_memory_usage > 70 %}
                                                background-color: #ffc107;
                                                {% else %}
                                                background-color: #198754;
                                                {% endif %}">
                                    </div>
                                    <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                                                display: flex; align-items: center; justify-content: center;
                                                color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                                        {{ device.snmp_memory_usage|floatformat:1 }}%
                                    </div>
                                </div>
                                {% else %}
                                --
                                {% endif %}
                            </td>
                            <td>{{ device.snmp_last_update|default_if_none:"--" }}</td>
                            <td>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-sm btn-primary dropdown-toggle" data-bs-toggle="dropdown">
                                        操作
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item" href="{% url 'network_device_edit' device.id %}">编辑</a></li>
                                        <li><a class="dropdown-item" href="#" onclick="deleteDevice({{ device.id }})">删除</a></li>
                                        {% if device.status == 'enabled' %}
                                        <li><a class="dropdown-item" href="#" onclick="toggleStatus({{ device.id }}, 'disable')">禁用</a></li>
                                        {% else %}
                                        <li><a class="dropdown-item" href="#" onclick="toggleStatus({{ device.id }}, 'enable')">启用</a></li>
                                        {% endif %}
                                    </ul>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
// 全选功能
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('.device-checkbox').forEach(checkbox => {
        checkbox.checked = this.checked;
    });
});

// 批量操作
function batchAction(action) {
    const selectedIds = Array.from(document.querySelectorAll('.device-checkbox:checked')).map(cb => cb.value);
    if (selectedIds.length === 0) {
        alert('请选择要操作的设备');
        return;
    }

    if (action === 'delete' && !confirm('确定要删除选中的设备吗？')) {
        return;
    }

    fetch('{% url "batch_update_network_devices" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            device_ids: selectedIds,
            action: action
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            location.reload();
        } else {
            alert(data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败');
    });
}

// 删除单个设备
function deleteDevice(id) {
    if (confirm('确定要删除这个设备吗？')) {
        fetch(`/monitor/network-device/${id}/delete/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
        .then(response => {
            if (response.ok) {
                location.reload();
            } else {
                alert('删除失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除失败');
        });
    }
}

// 切换设备状态
function toggleStatus(id, action) {
    fetch('{% url "batch_update_network_devices" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify({
            device_ids: [id],
            action: action
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            location.reload();
        } else {
            alert(data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败');
    });
}

// 获取CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 自动更新SNMP数据
function updateDeviceMetrics() {
    document.querySelectorAll('tr[data-id]').forEach(row => {
        const deviceId = row.getAttribute('data-id');
        fetch(`/monitor/network-device-list/?device_id=${deviceId}`, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                updateMetricsDisplay(row, data.data);
            }
        })
        .catch(error => console.error('Error:', error));
    });
}

// 更新显示的指标
function updateMetricsDisplay(row, data) {
    // CPU使用率更新
    if (data.cpu_usage !== null) {
        const bgColor = data.cpu_usage > 90 ? '#dc3545' : 
                       data.cpu_usage > 70 ? '#ffc107' : '#198754';
        row.querySelector('.cpu-usage').innerHTML = `
            <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                <div class="progress-bar progress-bar-striped" role="progressbar" 
                     style="width: ${data.cpu_usage}%; background-color: ${bgColor};">
                </div>
                <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                            display: flex; align-items: center; justify-content: center;
                            color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                    ${data.cpu_usage.toFixed(1)}%
                </div>
            </div>
        `;
    }

    // 内存使用率更新
    if (data.memory_usage !== null) {
        const bgColor = data.memory_usage > 90 ? '#dc3545' : 
                       data.memory_usage > 70 ? '#ffc107' : '#198754';
        row.querySelector('.memory-usage').innerHTML = `
            <div class="progress" style="height: 20px; background-color: #f8f9fa; position: relative;">
                <div class="progress-bar progress-bar-striped" role="progressbar" 
                     style="width: ${data.memory_usage}%; background-color: ${bgColor};">
                </div>
                <div style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; 
                            display: flex; align-items: center; justify-content: center;
                            color: #000; text-shadow: 1px 1px 2px rgba(255,255,255,0.5);">
                    ${data.memory_usage.toFixed(1)}%
                </div>
            </div>
        `;
    }
}

// 定期更新数据
setInterval(updateDeviceMetrics, 60000); // 每分钟更新一次
</script>
{% endblock %} 